<?php
/**
 * Created by PhpStorm.
 * User: 刘红波 <liuhb@cqjcdflzxsws.com>
 * Date: 2018/7/31
 * Time: 16:04
 */

namespace app\api\model;


use think\Model;

class WeUserCategory extends Model
{
    protected $autoWriteTimestamp = true;

    /**
     * @param $uid
     * @param bool $flag
     * @return array
     * @throws \think\exception\DbException
     */
    public static function userCate($uid, $flag = false)
    {
        $model = new self();
        $fields = 'c.id,c.name';
        if ($flag) {
            $data_list = $model->alias('uc')
                ->join('__WE_CATEGORY__ c', 'uc.category_id = c.id')
                ->where(['uc.user_id'=>$uid,'c.status'=>1,'c.is_delete'=>0,'uc.is_delete'=>0])
                ->field($fields)
                ->select();
            return empty($data_list) ? [] : collection($data_list)->toArray();
        } else {
            $data_list = $model->alias('uc')
                ->join('__WE_CATEGORY__ c','uc.category_id = c.id and uc.is_delete = 0 and uc.user_id = '.$uid.' and c.`status` = 1 and c.is_delete = 0 and c.is_verify = 1')
                ->join('__WE_TOPIC__ t','t.category_id = c.id and t.is_delete = 0 and t.`status` = 1','left')
                ->field('c.id,c.`name`,sum(CASE t.id WHEN t.id THEN 1 ELSE 0 END) as num')
                ->group('c.id')
                ->orderRaw('sum(CASE t.id WHEN t.id THEN 1 ELSE 0 END) desc')
//                ->fetchSql(true)
//                ->select();
//            echo $data_list;exit;
                ->paginate(5)->toArray();
            return empty($data_list['data']) ? [] : $data_list;
        }
    }

    /**
     * @param $uid
     * @return array
     */
    public static function userCateAll($uid)
    {
        $model = new self();
        $data_list = $model->alias('uc')
            ->join('__WE_CATEGORY__ c', 'uc.category_id = c.id and uc.user_id=\'' . $uid . '\' and c.status = \'1\' and c.is_delete = \'0\' and uc.is_delete = \'0\'')
            ->column('c.id');
        return $data_list;
    }
}